package edu.hcmus.sow.service;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.dao.ClientDAO;
import edu.hcmus.sow.dao.SiteDAO;
import edu.hcmus.sow.domain.Client;
import edu.hcmus.sow.domain.Site;
import edu.hcmus.sow.domain.User;
import edu.hcmus.sow.utils.SecurityUtil;

@Service
@Transactional
public class ClientService {
   @Autowired
   private ClientDAO clientDAO;

   @Autowired
   private SiteDAO siteDAO;

   @Autowired
   private UserService userService;

   public Client saveClient(Integer id, String name, String email, String phone, boolean status) {
      Client client = id == null ? new Client() : clientDAO.findById(id);
      client.setName(name);
      client.setContactEmail(email);
      client.setPhone(phone);
      client.setStatus(status ? "Y" : "N");
      User loggedUser = userService.getUserByID(SecurityUtil.getCurrentLoggedinUserID());
      client.setUpdatedDate(Calendar.getInstance());
      client.setUserByUpdatedBy(loggedUser);

      if (id == null) {
         client.setCreatedDate(Calendar.getInstance());
         client.setUserByCreatedBy(loggedUser);
         client = clientDAO.persist(client);
      }
      return client;
   }

   public Site saveSite(Client client, String subDomain) {
      if (client.getSite() != null) {
         client.getSite().setSubDomain(subDomain);
         siteDAO.merge(client.getSite());
         return client.getSite();
      }

      Site site = new Site();
      site.setSubDomain(subDomain);
      site.setClient(client);
      site = siteDAO.persist(site);
      return site;
   }

   public Site saveSite(int siteId, String subDomain, Integer numberOfUsers, Integer storageLimit, Date renewDate,
         String defaultLanguage, String shortDateFormat) {
      Site site = siteDAO.findById(siteId);

      site.setSubDomain(subDomain);
      site.setNumberOfUsers(numberOfUsers);
      site.setStorageLimit(storageLimit);
      Calendar cal = null;
      if (renewDate != null) {
         cal = Calendar.getInstance();
         cal.setTime(renewDate);
      }
      site.setRenewDate(cal);
      site.setDefaultLanguage(defaultLanguage);
      site.setShortDateFormat(shortDateFormat);

      return site;
   }

   public Client getClientByID(Integer id) {
      return clientDAO.findById(id);
   }

   public Site saveSite(Site site) {
      if (site != null) {
         siteDAO.merge(site);
         return site;
      }

      return site;
   }

   public boolean deleteClient(Integer id) {
      Client client = clientDAO.findById(id);
      if (client == null) {
         return false;
      }
      clientDAO.delete(client);
      return true;
   }

}
